<div id="add-friend" class="hide" style="height: 2.3em; width: auto; position: fixed; z-index: 10000000; padding: 5px">
<a href="#" class="btn btn-info">Add Friend</a>
</div>
<div class="well">
  <div class="tabbable">
	<ul class="nav nav-tabs">
     <li class="active"><a id="select_available_games" data-toggle="tab" href="#available_games">Newest Games</a></li>
     <li><a id="select_created_games" data-toggle="tab" href="#available_games">Created Games</a></li>
     <li><a id="select_friend_games" data-toggle="tab" href="#available_games">Friend Games</a></li>
     <li><a id="select_create_game" data-toggle="tab" href="#create_game">New Game</a></li>
  </ul>
  </div>
  <div class="tab-content">
  <div class="tab-pane" id="create_game" style="min-height: 32em">
    {% include "create_game.html" %}
  </div>
	<div class="tab-pane active" id="available_games" style="min-height: 32em">
		<div class="row lined">
		  <div class="span2 bolded">Name</div>
			<div class="span2 bolded">Created By</div>
			<div class="span2 bolded">Creation Time</div>
			<div class="span1 bolded">Players</div>
			<div class="span1 bolded">&nbsp</div>
			<div class="span1 bolded" style="text-align: right;"><a id="game-search" href="#"><i class="icon-search"></i></a></div>
		</div>
		<div class="row lined hide" id="search-bar">
      <div class="span2 bolded"><input class="span2" type="text"></div>
      <div class="span2 bolded"><input class="span2" type="text"></div>
      <div class="span2 bolded">
        <select class="span2">
          <option>Past Minute</option>
          <option>Past Hour</option>
          <option>Past 6 Hours</option>
          <option>Today</option>
          <option>This Week</option>
          <option>All Time</option>
        </select>
      </div>
      <div class="span1 bolded">
        <select class="span1">
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
      <div class="span1">
        <a class=" btn btn-warning" href="joinGame/?game_id={{ game.id }}">Find</a>
      </div>
      <div class="span1 bolded"></div>
    </div>
		{% for game in games %}
		<div class="row hide forfeit-alert" id="row_forfeit_{{ game.id }}">
      <div class="alert" style="width: 28em">
        <strong>Warning!</strong> Do you want to forfeit this game?&nbsp&nbsp<a class="btn" id="btn_forfeit_no_{{ game.id }}">No</a>&nbsp&nbsp<a id="btn_forfeit_yes_{{ game.id }}" class="btn yes">Yes</a>
      </div>
    </div>
    {% load custom_filters %}
		<div id="row_game_{{ game.id }}" rel="game_in_page_{{ forloop.counter|divminusone:7 }}"
		  class="row lined game_row {% if game.created_by_id == profile.id %}creator {% endif %}{{ game.friend_status }}">
		  <div class="span2">{{ game.name }}</div>
		  {% if profile.id == game.created_by_id %}
		    <div class="span2 username">{{ game.created_by }}</div>
		  {% else %}
		    <div class="span2 player_profile {{ game.friend_status }}" id="{{ game.created_by_id }}"
		      name="{{ game.created_by }}">{{ game.created_by }}</div>
			{% endif %}
			<div class="span2">{{ game.creation_time|date:"N j, Y, H:i" }}</div>
			 {% load custom_filters %}
			<div class="span1 dropdown" id="player_menu_{{ game.id }}">
			  <a href="#player_menu_{{ game.id }}" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
			    <i class="icon-user"></i>&nbsp<span id="player_count_{{ game.id }}">{{ game.players|length }}</span>
			  </a>
			  <ul class="dropdown-menu">
           <li>
           <table class="table table-striped">
	           <tr><th>Name</th><th>Score</th><th>Online</th></tr>
	           {% for player in game.players %}
	           <tr {% if player.id == profile.id %}id="player_status_{{ game.id }}"{% endif %}>
	             <td>
	             <div class="player_profile {{ player.friend_status }}{% if player.current_player %}username {% endif %}"
	               id="{{ player.id }}">
	                 {{ player.name|wordbreak:'15' }}
	             <div></td>
	             <td>{{ player.score }}</td>
	             <td>
	             {% if player.status == 'playing' %}
	               <span class='label label-success small disabled'>{{ player.status }}</span>
	             {% endif %}
	             {% if player.status == 'online' %}
	               <span class='label label-info small disabled'>{{ player.status }}</span>
	             {% endif %}
	             {% if player.status == 'offline' %}
	               <span class='label small disabled'>{{ player.status }}</span>
	             {% endif %}

	             </td>
	           </tr>
	           {% endfor %}
	         </table>
           </li>
         </ul>
			</div>
			{% if game.current_player %}
			  <div class="span1" id="play_game_{{ game.id }}">
			    <a class="btn" href="playGame/?game_id={{ game.id }}">Play &raquo;</a>
			  </div>
				<div class="span1">
				  <a id="forfeit_{{ game.id }}" rel='twipsy-quit-game' class="close" href="#" title="forfeit game">
				    <i style="vertical-align: bottom;" class="icon-remove"></i>
				  </a>
				</div>
			{% else %}
			  <div class="span1" id="play_game_{{ game.id }}">
			    <a class=" btn btn-primary" href="joinGame/?game_id={{ game.id }}">Join &raquo</a>
			  </div>
			  <div class="span1"></div>
			{% endif %}
			<script>
				$("#forfeit_{{ game.id }}").click(function(data) {
					$("#row_forfeit_{{ game.id }}").slideDown();
	       });
			</script>
		</div>
		<script>

	   $("#btn_forfeit_yes_{{ game.id }}").click(function(){
		   $.post("/quitGame/", {"game_id": '{{ game.id }}'})
         .success(function() {
        	 $("#row_forfeit_{{ game.id }}").slideUp();
        	 $("#player_status_{{ game.id }}").remove();
        	 var playerCount = parseInt($("#player_count_{{ game.id }}").text()) - 1;
        	 $("#player_count_{{ game.id }}").text(playerCount);

        	 if (playerCount == 0) {
        		 $("#row_game_{{ game.id }}").slideUp("fast", function() {
        			 $(this).remove();
        			 repaginate();
        		 });
        	 }

        	 else {
        		 $("#play_game_{{ game.id }}").html("<a class='btn btn-primary' href='joinGame/?game_id={{ game.id }}'>Join &raquo</a>");
        		 $("#forfeit_{{ game.id }}").fadeOut();
        	 }
       })
       .error(function() { alert("Oops... Unable to save data. Please refresh page"); });
	   });
	   $("#btn_forfeit_no_{{ game.id }}").click(function(){
	      $("#row_forfeit_{{ game.id }}").slideUp();
	   });
		</script>
		{% endfor %}
	</div>
	</div>
	<div class="pagination pagination-centered">
	  <ul id="pagination">
	    <li id="first_box"><a id="first_link" href="#">First</a></li>
	    <li id="prev_box" class="disabled"><a id="prev_link" href="#">Prev</a></li>
	    <li class="disabled hide" id="prev_more_box"><a id="prev_more_link" href="#">...</a></li>
	    {% for page in pages %}
	    <li id="page_box_{{ page }}" class="page_box">
	      <a class="page_link" id="page_link_{{ page }}" href="#" rel="{{ page }}">{{ page }}</a>
	    </li>
      {% endfor %}
	    <li class="disabled hide" id="next_more_box"><a id="next_more_link" href="#">...</a></li>
	    <li id="next_box"><a id="next_link" href="#">Next</a></li>
	    <li id="last_box"><a id="last_link" href="#">Last</a></li>
	  </ul>
	</div>
</div>
<script>
$(document).ready(function(){
	 window.page = 1;
	 initPagination({{ pages|length }});

	 function initPagination(pages) {
		 $("#page_box_1").addClass("active");

		 $('.page_link').click(function(event){
			 event.preventDefault();
			 $('.page_box').removeClass("active");
			 $(this).parent().addClass("active");
			 page = $(this).attr('rel');
			 $('.game_row').hide();
			 $('[rel="game_in_page_' + (page - 1) + '"]').show();

			 resizePaginator(pages);
		 });

		 $("#prev_link").click(function(event){
			 $("#page_link_" + (page - 1)).click();
			 event.preventDefault();
			 resizePaginator(pages);
		 });

		 $("#next_link").click(function(event){
	     $("#page_link_" + (parseInt(page) + 1)).click();
	     event.preventDefault();
	     resizePaginator(pages);
	   });

		 $("#first_link").click(function(event){
	     $("#page_link_1").click();
	     event.preventDefault();
	     resizePaginator(pages);
	   });

	   $("#last_link").click(function(event){
	     $("#page_link_" + pages).click();
	     event.preventDefault();
	     resizePaginator(pages);
	   });

	   $("#page_link_1").click();
	 }

	 function resizePaginator(pages) {
		 $(".forfeit-alert").hide();
		 $('.page_link').each(function(i, object) {
			 var myPage = parseInt($(object).attr('rel'));
       var middle = Math.max(page, 4);
       middle = Math.min(middle, pages - 3);

			 if (myPage > middle + 3 || myPage < middle - 3) {
				 $(object).hide();
			 }
			 else {
				 $(object).show();
			 }
			 if (page != 1 && pages != 0) {
	       $("#prev_box").removeClass("disabled");
	     }
	     else {
	       $("#prev_box").addClass("disabled");
	     }

	     if (page != pages && pages != 0) {
	       $("#next_box").removeClass("disabled");
	     }
	     else {
	       $("#next_box").addClass("disabled");
	     }

	     if (page < pages - 3) {
	    	  $("#next_more_box").show();
	     }
	     else {
	    	 $("#next_more_box").hide();
	     }

	     if (page > 4) {
          $("#prev_more_box").show();
       }
       else {
         $("#prev_more_box").hide();
       }

		 });
	 }

	 function rePaginate() {
		 var count = $(".game_row").not($(".hide")).length;

		 $(".game_row").removeAttr("rel");
		 $(".game_row").not($(".hide")).each(function(i, object) {
			  $(object).attr("rel", "game_in_page_" + Math.floor(i/7));
		 });

		 var pages = Math.ceil(count/7);
		 var html =
      "<li id='first_box'><a id='first_link' href='#'>First</a></li>" +
      "<li id='prev_box' class='disabled'><a id='prev_link' href='#'>Prev</a></li>" +
      "<li class='disabled hide' id='prev_more_box'><a id='prev_more_link' href='#'>...</a></li>";

     for (i = 1; (i <= pages || (i == 1 && pages == 0)); i++) {
    	 html +=
      "<li id='page_box_" + i + "' class='page_box'>" +
      "  <a class='page_link' id='page_link_" + i + "' href='#' rel='" + i + "'>" + i + "</a>" +
      "</li>"
     }
     html +=
    	"<li class='disabled hide' id='next_more_box'><a id='next_more_link' href='#'>...</a></li>" +
      "<li id='next_box'><a id='next_link' href='#'>Next</a></li>" +
      "<li id='last_box'><a id='last_link' href='#'>Last</a></li>";

     $("#pagination").html(html);
     initPagination(pages);
	 }

   $('.player_profile').each(function(i, object){
	    var myClone = $('#add-friend').clone();

	   if (!$(object).hasClass('username')) {
		   var toId = $(object).attr("id");
		   myClone.addClass("add_friend_" + toId);
	     if ($(object).hasClass('friends')) {
	   	   myClone.children([':a']).text("Friends");
	   	   myClone.children([':a']).removeClass("info");
	   	   myClone.children([':a']).addClass("disabled");
	     }

	     if ($(object).hasClass('received_request')) {
	       myClone.children([':a']).text("Request From Sender Pending");
	       myClone.children([':a']).removeClass("info");
	       myClone.children([':a']).addClass("disabled");
	      }

	     if ($(object).hasClass('pending_request')) {
	       myClone.children([':a']).text("Requested");
	       myClone.children([':a']).removeClass("info");
	       myClone.children([':a']).addClass("disabled");
	      }

		    myClone.children([':a']).click(function(){
		    	if (!$(this).hasClass("disabled")) {
			    	var toName = $(object).attr("name");
			    	var metadata = ["from:{{ profile.id }}", "to:" + $(object).attr("id")];
		        var playType = "add-friend";

		        $.post("/makePlay/", {"play_type":playType, "game_id":0, "metadata":metadata})
		        .success(function(data) {
		        	var playId = data["play_id"];

		        	var mex = "ADD_FRIEND|{{ profile.name }}|" + toId + "|" + "{{ profile.id }}|" + playId;
	            engineRef.sendMessage(mex, null, 5000);
		        });
	          $(".add_friend_" + toId).children([':a']).text("Requested");
	          $(".add_friend_" + toId).children([':a']).removeClass("info");
	          $(".add_friend_" + toId).children([':a']).addClass("disabled");

		    	}
		    });

		    $(object).append(myClone);
	      $(object).hover(function(){
	    	  $.data(this, "timer", setTimeout($.proxy(function() {
	    		  myClone.fadeIn();
	    		  }, this), 750));
	      }, function(){
	    	  clearTimeout($.data(this, "timer"));
	    	  myClone.fadeOut();
	      });
	    }
    });

   $("#select_created_games").click(function(){
       $('.game_row').addClass("hide");
       $('.creator').removeClass("hide");
       rePaginate();
   });

   $("#select_friend_games").click(function(){
       $('.game_row').addClass("hide");
       $('.friends').removeClass("hide");
       rePaginate();
   });

   $("#select_available_games").click(function(){
	   $('.game_row').removeClass("hide");
	   rePaginate();
   });

   function showAllRowsWithClassAndRepaginate(clazz) {
	   $(clazz).each(function(i, object) {
        $(object).show(1, function() {
          if (i == $(clazz).length - 1) {
            rePaginate();
          }
        });
      });
   }

   $("#select_create_game").click(function(){
     $('#pagination').html("");
   });

   $(function () {
      $("a[rel=twipsy-quit-game]").tooltip({
        live: true
      })
   });

   $("#game-search").click(function(){
	   if($("#search-bar").is(":hidden")){
		   $("#search-bar").slideDown("fast");
	   }
	   else {
		   $("#search-bar").slideUp("fast");
	   }
   });
})
</script>
